package cn.tanghom.app.oa.service.impl;

import cn.tanghom.app.oa.mapper.LeaveMapper;
import cn.tanghom.app.oa.model.Leave;
import cn.tanghom.app.oa.service.LeaveService;
import cn.tanghom.support.page.Pager;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 请假业务实现
 *
 * @author tanghom<tanghom@qq.com> on 2016/6/30
 */
@Service
public class LeaveServiceImpl implements LeaveService {

    @Resource
    private LeaveMapper leaveMapper;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    protected TaskService taskService;
    @Resource
    protected HistoryService historyService;
    @Resource
    protected RepositoryService repositoryService;
    @Resource
    private IdentityService identityService;

    @Override
    public void save(Leave leave) {
        leaveMapper.save(leave);
    }

    @Override
    public void update(Leave leave) {
        leaveMapper.update(leave);
    }

    @Override
    public void delete(Long id) {
        leaveMapper.delete(id);
    }

    @Override
    public Leave findById(Long id) {
        return leaveMapper.findById(id);
    }

    @Override
    public Pager<Leave> findPageByParams(Long userId, Integer status, Long index) {
        Pager<Leave> pager = new Pager<Leave>();
        pager.setIndex(index);
        pager.setSize(10);
        List<Leave> leaveList = leaveMapper.findPageByParams(userId, status, pager.startRow(), pager.getSize());
        pager.setItems(leaveList);
        Long totalRecord = leaveMapper.countByParams(userId, status);
        pager.setTotalRecord(totalRecord);
        return pager;
    }

    @Override
    public ProcessInstance startWorkflow(Leave entity, Map<String, Object> variables) {
        leaveMapper.save(entity);
        String businessKey = entity.getId().toString();
        ProcessInstance processInstance = null;
        try {
            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            identityService.setAuthenticatedUserId(entity.getUser().getLoginName());
            processInstance = runtimeService.startProcessInstanceByKey("leave", businessKey, variables);
            String processInstanceId = processInstance.getId();
            entity.setProcessInstanceId(processInstanceId);
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        leaveMapper.update(entity);
        return processInstance;
    }
}
